package com.mugui.base.client.net.bagsend;

import com.mugui.base.base.Component;
import com.mugui.base.client.net.auto.AutoTask;
import com.mugui.base.client.net.base.Task;
import com.mugui.base.client.net.bean.Message;
import com.mugui.base.client.net.task.TaskImpl;
import lombok.Setter;

import java.util.concurrent.ConcurrentHashMap;

import static com.mugui.base.client.net.base.Task.CYCLE;

@Component
@Task(value = CYCLE, blank = 1000)
@AutoTask
public class WsOutTimeTask extends TaskImpl {


    static ConcurrentHashMap<NetCall, Long> netCalls = new ConcurrentHashMap<>();

    public void add(NetCall netCall) {
        if(netCall==null){
            return;
        }
        netCalls.put(netCall, System.currentTimeMillis());
    }

    public void del(NetCall netCall) {
        if(netCall==null){
            return;
        }
        netCalls.remove(netCall);
    }

    @Setter
    private long outTime = 30000;

    @Override
    public void run() {
        netCalls.forEach((netCall, aLong) -> {
            String threadName = netCall.getThreadName();
            Thread.currentThread().setName(threadName+"-WsOutTimeTask");
            if (System.currentTimeMillis() - aLong > outTime) {
                System.err.println("超时:"+netCall.getId());
                NetCall.Call son = netCall.getSon();
                if (son != null) {
                    son.err(new Message().setType(Message.ERROR).setMsg("超时"));
                }
                NetCall.Call main = netCall.getMain();
                if (main != null) {
                    main.err(new Message().setType(Message.ERROR).setMsg("超时"));
                }
                netCalls.remove(netCall);
            }
        });
    }
}
